package com.auerdi.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.telephony.TelephonyManager;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.auerdi.BuildConfig;

import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class Tool {

    public static final String VALIDATE_LOCATION = "-1.0";

    public static String ILLEGAL_INPUT_PATTER = "[^.,@_*\"';%]*";
    public static String SQL_REPLACE_PATTER = "[*_%@]";
    private static String[] PERMISSIONS_STORAGE = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static final int REQUEST_EXTERNAL_STORAGE = 1;


    /**
     * 获得全球唯一码UUID
     */
    public static String getUUID() {

        UUID uuid = UUID.randomUUID();

        String str = uuid.toString();

        String temp = str.substring(0, 7) + str.substring(9, 13)
                + str.substring(14, 18) + str.substring(19, 23)
                + str.substring(24);

        return temp;
    }

    public static String getTime(long time, String format) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.SIMPLIFIED_CHINESE);

        String text = dateFormat.format(new Date(time));
        return text;
    }

    /**
     * 判断网络连接是否存在
     */
    @SuppressLint("NewApi")
    public static boolean hasInternet(Context context) {

        ConnectivityManager manager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo info = manager.getActiveNetworkInfo();

        if (info == null || !info.isConnected()) {
            return false;
        }
        if (info.isRoaming()) {
            return true;
        }
        return true;
    }

    /**
     * 获取版本号
     */
    public static String getAPPVersion(Context context) {
        return BuildConfig.VERSION_NAME;
    }

    /**
     * 获取手机型号
     *
     * @return
     */
    public static String getMOBILE_MODEL() {
        return android.os.Build.MODEL == null ? "-1" : android.os.Build.MODEL;
    }

    /**
     * 获取设备系统版本
     */
    public static String getSYSTEM() {
        return android.os.Build.VERSION.RELEASE == null ? "-1"
                : android.os.Build.VERSION.RELEASE;
    }

    /**
     * 获取厂商
     *
     * @return
     */
    public static String getManufacturer() {
        return android.os.Build.MANUFACTURER == null ? "-1"
                : android.os.Build.MANUFACTURER;
    }

    /**
     * @return
     * @Title: getSimOperatorName
     * @Description: 获取运营商信息
     * @Author:LR
     */
    public static String getOperator(Context context) {
        String operator = "-1";
        try {
            TelephonyManager telMgr = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            operator = telMgr.getNetworkOperatorName();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return operator;
    }

    /**
     * 获取IMSI(SIM卡唯一识别标志)
     */
//    public static String getIMSI(Context context) {
//        String imsi = "-1";
//        try {
//            TelephonyManager telManager = (TelephonyManager) context
//                    .getSystemService(Context.TELEPHONY_SERVICE);
//            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//                // TODO: Consider calling
//                //    ActivityCompat#requestPermissions
//                // here to request the missing permissions, and then overriding
//                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                //                                          int[] grantResults)
//                // to handle the case where the user grants the permission. See the documentation
//                // for ActivityCompat#requestPermissions for more details.
//                return TODO;
//            }
//            imsi = telManager.getSubscriberId();
//            if (null == imsi) {
//                imsi = "-1";
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return imsi;
//    }

    /**
     * 获取IMEI(deviceID)
     *
     * @param context
     * @return
     */
//    public static String getIMEI(Context context) {
//        String imei = "-1";
//        try {
//            TelephonyManager telMgr = (TelephonyManager) context
//                    .getSystemService(Context.TELEPHONY_SERVICE);
//            imei = telMgr.getDeviceId();
//            if (imei == null) {
//                imei = "-1";
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return imei;
//    }

    /**
     * 根据传入的分隔符参数将字符串分割并传入数组;
     *
     * @param regex  :分隔符;
     * @param string :字符串;
     * @return
     */
    public static String[] split(String regex, String string) {
        if (regex == null || string == null) {
            return null;
        }

        Vector<String> vector = new Vector<String>();
        int index = string.indexOf(regex);

        if (index == -1) {
            vector.addElement(string);
        } else {
            while (index != -1) {
                vector.addElement(string.substring(0, index));
                string = string.substring(index + 1, string.length());
                index = string.indexOf(regex);
            }

            if (index != string.length() - 1) {
                vector.addElement(string);
            }
        }

        final String[] array = new String[vector.size()];
        vector.copyInto(array);
        vector = null;

        return array;
    }

    public static void zipFiles(String outputZipFile, String filesPath) {

        BufferedInputStream br = null;

        int ZIP_BUFFER_SIZE = 1024;
        try {
            FileOutputStream fos = new FileOutputStream(outputZipFile);
            ZipOutputStream zos = new ZipOutputStream(fos);
            zos.setMethod(ZipOutputStream.DEFLATED);
            byte[] data = new byte[ZIP_BUFFER_SIZE];
            File f = new File(filesPath);
            String files[] = f.list();
            for (int i = 0; i < files.length; i++) {
                // System.out.println("Adding: " + files[i]);
                FileInputStream fi = new FileInputStream(filesPath
                        + File.separator + files[i]);
                br = new BufferedInputStream(fi, ZIP_BUFFER_SIZE);
                ZipEntry entry = new ZipEntry(files[i]);
                zos.putNextEntry(entry);
                int count;
                while ((count = br.read(data, 0, ZIP_BUFFER_SIZE)) != -1) {
                    zos.write(data, 0, count);
                }
                zos.closeEntry();
                br.close();
                fi.close();
                fi = null;
                br = null;
            }
            zos.close();
            zos = null;
        } catch (Exception e) {
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                br = null;
            }
        }
    }

    /**
     * 字符串按字符截取
     *
     * @param str   要截取的字符串
     * @param len   截取长度最大值
     * @param elide 附加值：省略符等追加到截取完的后边
     * @return
     */
    public static String subString(String str, int len, String elide) {

        if (str != null && len != 0) {
            int length = str.length();
            if (length >= len) {
                return str.substring(0, len - 1) + elide.trim();
            } else {
                return str;

            }

        } else {
            return "";
        }
    }

    /**
     * 验证邮箱
     *
     * @return
     */
    public static boolean matchEmail(String emailStr) {
        String emailExp = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(emailExp);
        Matcher m = p.matcher(emailStr);
        return m.matches();
    }

    /**
     * 是否包含字母
     *
     * @return
     */
    private static boolean hasLetter(String str) {
        int len = str.length();
        for (int i = 0; i < len; i++) {
            char chr = str.charAt(i);
            if ((chr >= 0x41 && chr <= 0x5A) || (chr >= 0x61 && chr <= 0x7A)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 是否包含数字
     *
     * @return
     */
    private static boolean hasNumeric(String str) {
        int len = str.length();
        for (int i = 0; i < len; i++) {
            char chr = str.charAt(i);
            if (chr >= 0x30 && chr <= 0x39) {
                return true;
            }
        }

        return false;
    }

    /**
     * 验证是否符合password规则
     *
     * @return
     */
    public static boolean matchPwdRule(String pwdStr) {
        return (hasNumeric(pwdStr) && hasLetter(pwdStr));
    }

    /**
     * @param date
     * @return 年月日
     */
    public static String date(long date) {
        SimpleDateFormat bartDateFormat =

                new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINESE);

        Date datetime = new Date(date);

        // bartDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));

        return bartDateFormat.format(datetime);
    }

    public static String formatDate(Date date) {

        if (date != null) {
            SimpleDateFormat bartDateFormat =

                    new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE);

            return bartDateFormat.format(date);
        }
        return "";
    }


    public static String dateFormat(Date date) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINESE).format(date);
    }

    public static Date parseTime(String time) {
        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINESE).parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String dateTime(long date) {
        SimpleDateFormat bartDateFormat =

                new SimpleDateFormat("yyyy年MM月dd日" + " HH:mm", Locale.CHINESE);

        Date datetime = new Date(date);

        return bartDateFormat.format(datetime);
    }

    /**
     * 校验JSON数据的值是否为空若为空则返回""否则返回相应的值
     *
     * @throws org.json.JSONException
     */

    public static String getString(JSONObject obj, String key) {
        String value = "";
        if (obj.opt(key) != JSONObject.NULL) {
            value = obj.optString(key);
        }
        return value;
    }

    public static void hideSoftInput(Activity activity) {
        if (activity != null && !activity.isFinishing()) {
            WindowManager.LayoutParams params = activity.getWindow()
                    .getAttributes();
            if (params.softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) {
                InputMethodManager imm = (InputMethodManager) activity
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
            InputMethodManager im = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (im != null && activity != null && activity.getCurrentFocus() != null) {
                im.hideSoftInputFromWindow(activity.getCurrentFocus().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    public static void hideSoftInput(Activity activity, View view) {
        if (activity != null && !activity.isFinishing()) {

            WindowManager.LayoutParams params = activity.getWindow()
                    .getAttributes();

            InputMethodManager imm = (InputMethodManager) activity
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (params.softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) {
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            } else {
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }

    public static void showSoftInput(Activity activity, View view) {
        if (activity != null && !activity.isFinishing()) {

            WindowManager.LayoutParams params = activity.getWindow()
                    .getAttributes();

            InputMethodManager imm = (InputMethodManager) activity
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (params.softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
                imm.toggleSoftInput(0, InputMethodManager.RESULT_SHOWN);
            } else {
                imm.showSoftInput(view, InputMethodManager.RESULT_SHOWN);
            }
        }
    }

    public static void hideSoftInputBoard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * @param s 取md5
     * @return
     */
    public static String getMd5(String s) { //将 字符串 s 进行MD5编码
        char hexDigits[] = {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            byte[] strTemp = s.getBytes();
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(strTemp);
            byte[] md = messageDigest.digest();

            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 启动外部浏览器打电话
     */
    public static void call(Activity activity, String phone) {

        if (activity == null || activity.isFinishing() || TextUtils.isEmpty(phone))
            return;

        try {
            Intent phoneIntent = new Intent("android.intent.action.DIAL", Uri.parse("tel:" + phone));
            activity.startActivity(phoneIntent);
        } catch (Exception e) {
        }
    }

    /**
     * 跳转发送短信界面
     */
    public static void sms(Activity activity, String number) {
        if (activity == null || activity.isFinishing() || TextUtils.isEmpty(number))
            return;
        try {
            Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + number));
            activity.startActivity(sendIntent);
        } catch (Exception e) {
        }
    }

    /**
     * 跳转发送短信界面附带内容
     */
    public static void sendSmsWithBody(Activity activity, String number, String body) {
        if (activity == null || activity.isFinishing() || TextUtils.isEmpty(number))
            return;
        try {
            Intent sendIntent = new Intent(Intent.ACTION_SENDTO);
            sendIntent.setData(Uri.parse("smsto:" + number));
            sendIntent.putExtra("sms_body", body);
            activity.startActivity(sendIntent);
        } catch (Exception e) {
        }
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
//    public static int dip2px(float dpValue) {
//        final float scale = UzenithTinkerApplicationLike.sGlobalContext.getResources().getDisplayMetrics().density;
//        return (int) (dpValue * scale + 0.5f);
//    }
//
//    /**
//     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
//     */
//    public static int px2dip(float pxValue) {
//        final float scale = UzenithTinkerApplicationLike.sGlobalContext.getResources().getDisplayMetrics().density;
//        return (int) (pxValue / scale + 0.5f);
//    }
//
//    public static float dp2px(int dip) {
//        DisplayMetrics dm = UzenithTinkerApplicationLike.sGlobalContext.getResources().getDisplayMetrics();
//        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, dm);
//    }
//
//    public static float sp2px(int sp) {
//        DisplayMetrics dm = UzenithTinkerApplicationLike.sGlobalContext.getResources().getDisplayMetrics();
//        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, dm);
//    }
    public static boolean check(Activity activity) {
        if (activity != null && !activity.isFinishing()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param strInt
     * @return null or empty return 0
     */
    public static int parseInt(String strInt) {
        return parseInt(strInt, 0);
    }

    /**
     * @param strInt
     * @return null or empty return defaultValue
     */
    public static int parseInt(String strInt, int defaultValue) {
        if (strInt == null || "".equals(strInt))
            return defaultValue;
        try {
            return Integer.parseInt(strInt);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static double parserDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (NumberFormatException e) {
            return 0;
        } catch (NullPointerException e) {
            return 0;
        }

    }

    public static double sub(double d1, double d2) {

        BigDecimal bd1 = new BigDecimal(Double.toString(d1));
        BigDecimal bd2 = new BigDecimal(Double.toString(d2));
        return bd1.subtract(bd2).doubleValue();

    }

    public static double sum(double d1, double d2) {
        BigDecimal bd1 = new BigDecimal(Double.toString(d1));
        BigDecimal bd2 = new BigDecimal(Double.toString(d2));
        return bd1.add(bd2).doubleValue();
    }

    public static String format1(double value) {

        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(1, RoundingMode.HALF_UP);
        return bd.toString();
    }


    /**
     * check whether be empty/null or not
     *
     * @param string
     * @return
     */
    public static boolean isEffective(String string) {
        if ((string == null) || ("".equals(string)) || (" ".equals(string))
                || ("null".equals(string)))
            return false;
        else
            return true;
    }

    public static boolean isEffective(List list) {
        if (list != null && list.size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isEffective(Activity content) {
        if (content == null || content.isFinishing()) {
            return false;
        } else {
            return true;
        }
    }

    public static boolean isEffective(Object object) {
        if (object == null) {
            return false;
        } else {
            return true;
        }
    }

    public static boolean isActivityRunning(Context mContext, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager)
                mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList
                = activityManager.getRunningServices(30);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    public static boolean isEffective(Fragment context) {
        return context != null && !context.isDetached();
    }

    public static Calendar getTomorrow() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar;
    }

    public static Calendar getToday() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 0);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar;
    }

    public static Calendar getYesterday() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar;
    }

    public static Calendar get7day() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 7);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar;
    }

    public static String getNextDay() {
        Date date = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, 1);
        date = calendar.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
        String dateString = formatter.format(date);
        return dateString;
    }

    public static String getTime() {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-M-d");
        String time = format.format(date);
        return time;
    }

    public static String getCurrentTime() {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date);
        return time;
    }

    public static String getDay() {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String time = format.format(date);
        return time;
    }

    public static String get1Yesterday() {
        Date date = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, -1);
        date = calendar.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
        String dateString = formatter.format(date);
        return dateString;
    }

    public static String get2Yesterday() {
        Date date = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, -2);
        date = calendar.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
        String dateString = formatter.format(date);
        return dateString;
    }

    public static String get3Yesterday() {
        Date date = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, -3);
        date = calendar.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
        String dateString = formatter.format(date);
        return dateString;
    }

    public static String getMonth() {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM");
        String time = format.format(date);
        return time;
    }

    public static String subMonth(String date) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            Date dt = sdf.parse(date);
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(dt);
            rightNow.add(Calendar.MONTH, -1);
            Date dt1 = rightNow.getTime();
            String reStr = sdf.format(dt1);
            return reStr;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String sumMonth(String date) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            Date dt = sdf.parse(date);
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(dt);
            rightNow.add(Calendar.MONTH, +1);
            Date dt1 = rightNow.getTime();
            String reStr = sdf.format(dt1);
            return reStr;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String dateStr(long time) {
        SimpleDateFormat bartDateFormat =
                new SimpleDateFormat("yyyy-MM-dd");
        Date datetime = new Date(time);

        return bartDateFormat.format(datetime);
    }

    public static String getCallTime() {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date);
        return time;
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    public static boolean hasDigit(String content) {
        boolean flag = false;
        Pattern p = Pattern.compile(".*\\d+.*");
        Matcher m = p.matcher(content);
        if (m.matches()) {
            flag = true;
        }
        return flag;
    }

    public static double divide(String d1, String d2) {
        BigDecimal bd1 = new BigDecimal(d1);
        BigDecimal bd2 = new BigDecimal(d2);
        MathContext mc = new MathContext(2, RoundingMode.HALF_UP);
        BigDecimal result = bd1.divide(bd2, mc);
        return result.doubleValue();
    }

    public static double compareDouble(double d1, double d2) {
        BigDecimal bd1 = new BigDecimal(Double.toString(d1));
        BigDecimal bd2 = new BigDecimal(Double.toString(d2));
        return bd1.compareTo(bd2);
    }

    /**
     * 需要设小数和整数区分的edittext需要设置此参数
     *
     * @param map 单位，edittext
     */
    public static void setNumberInput(Map<String, EditText> map) {
        Iterator<Map.Entry<String, EditText>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, EditText> entry = it.next();
            if (entry.getKey().equals("KG") || entry.getKey().equals("M") || entry.getKey().equals("Z03") || entry.getKey().equals("Z09")) {
                if (entry.getValue() instanceof EditText) {
                    entry.getValue().setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                }
            } else {
                entry.getValue().setInputType(InputType.TYPE_CLASS_NUMBER);
            }
        }
    }


    public static boolean stringEqual(String str1, String str2) {
        if (str1 != null && str2 != null) {
            if (str1.equals(str2)) {
                return true;
            }
        }
        return false;
    }

    //获取Mac地址
    public static String getLocalMacAddress(Context context) {
        if (Tool.isEffective(context)) {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            if (wifiManager != null) {
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                if (wifiInfo != null) {
                    return wifiInfo.getMacAddress();
                }
            }
        }
        return "";
    }

    public static String getModel() {
        return android.os.Build.MODEL;
    }

    public static String longTodate(Long currentTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(currentTime);
        return formatter.format(date);
    }

    public static String longTodateConvert(Long currentTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(currentTime);
        return formatter.format(date);
    }

    public static String longToMinConvert(Long currentTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date(currentTime);
        return formatter.format(date);
    }

    public static boolean isDecimal(String str) {
        Pattern pattern = Pattern.compile("\\d+\\.\\d+$|-\\d+\\.\\d+$");//判断是否为小数
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    public static String getFormat13(String result) {
        if (Tool.isEffective(result)) {
            String resultMatchKg = result.substring(7, 9) + "." + result.substring(9, 12);
            return String.format("%.3f", Double.valueOf(resultMatchKg));
        }
        return "";
    }

    public static String getFormat18(String result) {
        if (Tool.isEffective(result)) {
            String resultMatchKg = result.substring(12, 14) + "." + result.substring(14, 17);
            return String.format("%.3f", Double.valueOf(resultMatchKg));
        }
        return "";
    }


    public static boolean detectScanBarcode(String scanResult, String barCode, String scaleCode, StringBuffer weight) {
        if (!Tool.isEffective(scanResult)) {
            return false;
        }
        if (weight == null) {
            weight = new StringBuffer();
        } else {
            weight.setLength(0);
        }

        if (isEffective(scaleCode) && scanResult.length() == 18) {
            if (scanResult.substring(2, 7).equals(scaleCode)) {
                weight.append(getFormat18(scanResult));
                return true;
            }
        }

        if (isEffective(barCode)) {
            String[] codeNum = barCode.split(",");

            for (int j = 0; j < codeNum.length; j++) {
                if (scanResult.equals(codeNum[j])
                        || (codeNum[j].length() == 8
                        && scanResult.startsWith(codeNum[j].substring(0, 7)))) {
                    if (scanResult.length() == 13) {
                        weight.append(getFormat13(scanResult));
                    }
                    return true;
                }

            }
            if (scanResult.startsWith(barCode) && !isNumeric(scanResult.substring(0, 1))) {
                return true;
            }
//            if (barCode.length() == 8
//                    && scanResult.startsWith(barCode.substring(0, 7))) {
//                if(scanResult.equals(barCode)) {
//                    weight.append(getFormat13(scanResult));
//                    return true;
//                }
//            }
        }


        return false;
    }

    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = new String(Base64.encode(bitmapBytes, Base64.NO_WRAP));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * Checks if the app has permission to write to device storage
     * <p/>
     * If the app does not has permission then the user will be prompted to grant permissions
     *
     * @param activity the activity from which permissions are checked
     */
    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

    //判断是不是英文字母
    public static boolean isEnglish(String charaString) {
        return charaString.matches("^[a-zA-Z]*");
    }

    /*
     * 判断是否为整数
     */
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    /**
     * @Description:把list转换为一个用逗号分隔的字符串
     */
    public static String listToString(List list) {
        StringBuilder sb = new StringBuilder();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (i < list.size() - 1) {
                    sb.append(list.get(i) + ",");
                } else {
                    sb.append(list.get(i));
                }
            }
        }
        return sb.toString();
    }

    /**
     * 将sample工程需要的资源文件拷贝到SD卡中使用（授权文件为临时授权文件，请注册正式授权）
     *
     * @param isCover 是否覆盖已存在的目标文件
     * @param source
     * @param dest
     */
    public static void copyFromAssetsToSdcard(Context context, boolean isCover, String source, String dest) {
        File file = new File(dest);
        if (isCover || (!isCover && !file.exists())) {
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                is = context.getResources().getAssets().open(source);
                String path = dest;
                fos = new FileOutputStream(path);
                byte[] buffer = new byte[1024];
                int size = 0;
                while ((size = is.read(buffer, 0, 1024)) >= 0) {
                    fos.write(buffer, 0, size);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void makeDir(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public static Bitmap getLocalBitmap(String uri) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
//        newOpts.inSampleSize = 4;
        newOpts.inJustDecodeBounds = false;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;

        Bitmap bmp = BitmapFactory.decodeFile(uri, newOpts);
        return bmp;
    }

    public static Bitmap getBitmapFormUri(Activity ac, Uri uri) throws FileNotFoundException, IOException {
        InputStream input = ac.getContentResolver().openInputStream(uri);
        BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
        onlyBoundsOptions.inJustDecodeBounds = true;
        onlyBoundsOptions.inDither = true;//optional
        onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
        input.close();
        int originalWidth = onlyBoundsOptions.outWidth;
        int originalHeight = onlyBoundsOptions.outHeight;
        if ((originalWidth == -1) || (originalHeight == -1))
            return null;
        //图片分辨率以480x800为标准
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (originalWidth > originalHeight && originalWidth > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (originalWidth / ww);
        } else if (originalWidth < originalHeight && originalHeight > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (originalHeight / hh);
        }
        if (be <= 0)
            be = 1;
        //比例压缩
        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
        bitmapOptions.inSampleSize = be;//设置缩放比例
        bitmapOptions.inDither = true;//optional
        bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        input = ac.getContentResolver().openInputStream(uri);
        Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
        input.close();

        return compressImage(bitmap);//再进行质量压缩
    }

    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            //第一个参数 ：图片格式 ，第二个参数： 图片质量，100为最高，0为最差  ，第三个参数：保存压缩后的数据的流
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    public static Bitmap loadBitmap(String url) {
        Bitmap bm = null;
        InputStream is = null;
        BufferedInputStream bis = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            conn.connect();
            is = conn.getInputStream();
            bis = new BufferedInputStream(is, 8192);
            bm = BitmapFactory.decodeStream(bis);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bm;
    }

    /**
     * 获取屏幕尺寸
     */
    public static int getWindowWidth(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        dm = context.getResources().getDisplayMetrics();

        // float density = dm.density; // 屏幕密度（像素比例：0.75/1.0/1.5/2.0）
        // int densityDPI = dm.densityDpi; // 屏幕密度（每寸像素：120/160/240/320）
        // float xdpi = dm.xdpi;
        // float ydpi = dm.ydpi;

        int screenWidth = dm.widthPixels; // 屏幕宽（像素，如：480px）

        return screenWidth;
    }

    public static int getWindowHeight(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        dm = context.getResources().getDisplayMetrics();

        // float density = dm.density; // 屏幕密度（像素比例：0.75/1.0/1.5/2.0）
        // int densityDPI = dm.densityDpi; // 屏幕密度（每寸像素：120/160/240/320）
        // float xdpi = dm.xdpi;
        // float ydpi = dm.ydpi;

        int screenHeight = dm.heightPixels; // 屏幕高（像素，如：800px）

        return screenHeight;
    }

    public static String getImageStr(File imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理

        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
//        NewBase64 base64=new NewBase64();
//        return base64.encode(data);
        return new String(Base64.encode(data, Base64.NO_WRAP));
    }

    /**
     * 百度地图坐标转高德地图
     *
     * @param bd_lon 经度（值较大）
     * @param bd_lat 纬度（值较小）
     */

    public static String bd_decrypt(double bd_lon, double bd_lat) {
        double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        double x = bd_lon - 0.0065, y = bd_lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        return z * Math.cos(theta) + "," + z * Math.sin(theta);
    }

    /**
     * 验证手机号码是否合法
     * 176, 177, 178;
     * 180, 181, 182, 183, 184, 185, 186, 187, 188, 189;
     * 145, 147;
     * 130, 131, 132, 133, 134, 135, 136, 137, 138, 139;
     * 150, 151, 152, 153, 155, 156, 157, 158, 159;
     * <p>
     * "13"代表前两位为数字13,
     * "[0-9]"代表第二位可以为0-9中的一个,
     * "[^4]" 代表除了4
     * "\\d{8}"代表后面是可以是0～9的数字, 有8位。
     */
    public static boolean isMobileNumber(String mobiles) {
        String telRegex = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147,145))\\d{8}$";
        return !TextUtils.isEmpty(mobiles) && mobiles.matches(telRegex);
    }


}